package com.fmi.timedealer.achievement;

import java.text.DecimalFormat;
import java.util.ArrayList;

import com.fmi.timedealer.R;
import com.fmi.timedealer.datamanager.IDataManager;
import com.fmi.timedealer.datamanager.SQLiteDataManager;

import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;

public class LevelsActivity extends ListActivity {
	
	private ArrayList<AchievementLevel> levels = null;
	private IDataManager dbManager = null;
	private LevelAdapter adapter = null;
	private Achievement currentAchievement = null;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.levels);
		
		Bundle extras = getIntent().getExtras();
		currentAchievement = (Achievement)extras.getSerializable(AchievementsActivity.ACHIEVEMENT_BUNDLE_KEY);
		
		if (currentAchievement != null) {
			this.setTitle(this.getTitle() + " for " + currentAchievement.getName());
		}
		
		dbManager = new SQLiteDataManager("MyDB", this);
		levels = dbManager.getLevelsForId(currentAchievement.getId());
		currentAchievement.setLevels(levels);
		refreshAdapter();
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
	    inflater.inflate(R.menu.levels_menu, menu);
	    return true;
    }
	
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		
		switch (item.getItemId()) {
	        
			case R.id.add_level: {
	        	Intent i = new Intent(LevelsActivity.this, ManageLevelActivity.class);
	        	i.putExtra(AchievementsActivity.ACHIEVEMENT_ID_BUNDLE_KEY, currentAchievement.getId());
				i.putExtra(AchievementsActivity.LEVEL_BUNDLE_KEY, new AchievementLevel(currentAchievement.getMaxLevel() + 1));
				startActivityForResult(i, AchievementsActivity.ACTION_REQUEST_CODE);
	        	return true;
	        }
	        default:
	            return super.onOptionsItemSelected(item);
	    }
	}
	
	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);
		
		AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)menuInfo;
		menu.setHeaderTitle("Level " + levels.get(info.position).getLevel() + ": " + levels.get(info.position).getName());
		
		MenuInflater inflater = getMenuInflater();
	    inflater.inflate(R.menu.manage_level, menu);
	}
	
	@Override
	public boolean onContextItemSelected(MenuItem item) {
	    
		AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
	    
		switch (item.getItemId()) {
	        case R.id.edit_level: {
	        	Intent i = new Intent(LevelsActivity.this, ManageLevelActivity.class);
	        	i.putExtra(AchievementsActivity.ACHIEVEMENT_ID_BUNDLE_KEY, currentAchievement.getId());
				i.putExtra(AchievementsActivity.LEVEL_BUNDLE_KEY, levels.get(info.position));
				startActivityForResult(i, AchievementsActivity.ACTION_REQUEST_CODE);
	        	return true;
	        }
	        case R.id.delete_level: {
	            deleteLevel(info.position);
	        	return true;
	        }
	        default:
	            return super.onContextItemSelected(item);
	    }
	}
	
	private void refreshAdapter() {
		adapter = new LevelAdapter(this, R.layout.item_row, levels);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		setListAdapter(adapter);
		
		ListView lv = getListView();
		registerForContextMenu(lv);
		
		// On Level click
		lv.setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				Intent i = new Intent(LevelsActivity.this,
						LevelItemsActivity.class);
				i.putExtra(AchievementsActivity.LEVEL_BUNDLE_KEY,
						levels.get(position));
				startActivityForResult(i,
						AchievementsActivity.ACTIVITIES_REQUEST_CODE);
			}
		});
		adapter.notifyDataSetChanged();
	}
	
	@Override
	public void onResume() {
		super.onResume();
		refreshAdapter();
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {

		if (requestCode == AchievementsActivity.ACTION_REQUEST_CODE) {
			if (resultCode == RESULT_OK) {
				Bundle extras = data.getExtras();
				AchievementLevel level = (AchievementLevel)extras.getSerializable(AchievementsActivity.LEVEL_BUNDLE_KEY);
				
				updateLevel(level);
			}
		}
	}
	
	private void updateLevel(AchievementLevel level) {
		
		int position = -1;
		for (int i = 0; i < levels.size(); i++) {
			if (levels.get(i).getId() == level.getId()) {
				position = i;
				break;
			}
		}
		
		if (position < 0) {
			// Add new object to the collection
			levels.add(level);
		}
		else {
			// Update object 
			levels.set(position, level);
		}
		currentAchievement.setLevels(levels);
		Toast.makeText(this, "Level " + level.getLevel() + ": " + level.getName() + " was successfully saved", Toast.LENGTH_SHORT).show();
		this.onResume();
	}

	private void deleteLevel(int position) {
		boolean deleted = dbManager.deleteLevel(levels.get(position), currentAchievement.getId());
		if (deleted) {
			AchievementLevel deletedLevel = levels.get(position);
			levels.remove(position);
			refreshAdapter();
			
			Toast.makeText(this, "Level " + deletedLevel.getLevel() + ": " + deletedLevel.getName() + " was successfully deleted", Toast.LENGTH_SHORT).show();
		}
	}
	
	private class LevelAdapter extends ArrayAdapter<AchievementLevel> {
		
        private ArrayList<AchievementLevel> items;

        public LevelAdapter(Context context, int textViewResourceId, ArrayList<AchievementLevel> items) {
                super(context, textViewResourceId, items);
                this.items = items;
        }
        
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
                
        	View v = convertView;
                if (v == null) {
                    LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                    v = vi.inflate(R.layout.item_row, null);
                }
                
                AchievementLevel lvl = items.get(position);

                if (lvl != null) {
                        TextView tvName = (TextView)v.findViewById(R.id.itemName);
                        TextView tvInfo = (TextView)v.findViewById(R.id.itemInfo);
                        TextView tvStatus = (TextView)v.findViewById(R.id.itemStatus);
                        ProgressBar progressBar = (ProgressBar)v.findViewById(R.id.itemProgressBar);
                        
                        int progress = getProgress(lvl);
                        progressBar.setProgress(progress);
                        
                        if (tvName != null) {
                        	tvName.setText(lvl.getName());
                    	}
                        if (tvInfo != null){
                        	tvInfo.setText("Level " + lvl.getLevel());
                        }
                        if (tvStatus != null) {
                        	tvStatus.setText("Progress: " + progress + "%");
                        }
                        
                }
                return v;
        }
	}
	
	private int getProgress(AchievementLevel level) {
		int progress = 0;
		try {
			ArrayList<AchievementLevelItem> levelItems = dbManager.getLevelItemsForId(level.getId());
			int remaining = 0, goal = 0;
			for (AchievementLevelItem levelItem : levelItems) {
				remaining += levelItem.getRemainingTime();
				goal += levelItem.getGoalTrackTime();
			}
			
			int current = goal - remaining;
	    	Double ddd = (double) (((double)current / (double)goal) * 100);
	    	DecimalFormat twoDForm = new DecimalFormat("#.##");
	        ddd = Double.valueOf(twoDForm.format(ddd));
	        progress = ddd.intValue();
		} catch (Exception e) {
			Log.e(getClass().getSimpleName(), "Couldn't get the progress for level with id " + level.getId());
		}
		return progress;
	}

}
